/*
 * Module name : CatalogTreeView
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import CheckboxWidget from '../../widgets/CheckboxWidget.js';
import InputWidget from '../../widgets/InputWidget.js';
import CatalogTreeCollectionView from './CatalogTreeCollectionView.js';

const template = require('./templates/CatalogTreeView.mustache');

const CatalogTreeView = Mn.View.extend({
    template: template,
    regions: {
        selectToggle: '.select-toggle',
        filter: '.field-filter',
        treeContainer: '.tree-container',
    },
    ui: {},
    // Listen to the current's view events
    events: {

    },
    // Listen to child view events
    childViewEvents: {
        "change": "onFilterKeyUp",
        "finish": "onToggleChecked",
    },
    // Bubble up child view events
    childViewTriggers: {},
    initialize() {
        // store the visible models for the select all functionnality
        this._visibleModels = this.collection.models;
        this.session = Radio.channel('session');
    },
    onRender() {
        let value = this.session.request('get', 'catalogFilter', '');
        this.showChildView(
            'filter',
            new InputWidget({
                field_name: 'filter',
                placeholder: 'Rechercher par nom / référence / description',
                ariaLabel: 'Rechercher par nom / référence / description',
                label: "Rechercher un produit dans le catalogue",
                value: value
            })
        );
        this.showChildView(
            'treeContainer',
            new CatalogTreeCollectionView({
                collection: this.collection,
                childViewOptions: {
                    multiple: this.getOption('multiple'),
                }
            })
        );
        this.showToggleSelect();
    },
    onAttach() {
        // On restaure un filtre existant
        let value = this.session.request('get', 'catalogFilter', '');
        if (value.length > 1) {
            this.onFilterKeyUp('filter', value);
        }
    },
    showToggleSelect() {
        if (this.collection.length > 1) {
            this.showChildView(
                'selectToggle',
                new CheckboxWidget({
                    field_name: 'toggle',
                    title: "",
                    inlineLabel: "Sélectionner tous les produits / Aucun produit",
                    ariaLabel: "Sélectionner ou déselectionner tous les éléments",
                    true_val: true,
                    false_val: false,
                    toggle: false,
                    value: this.collection.allSelected()
                })
            );
        }
    },
    getFilter(value) {
        this._visibleModels = [];
        return (view, index, children) => {
            if (view.model.matchPattern(value) || view.model.get('selected')) {
                this._visibleModels.push(view.model);
                return true;
            }
        }
    },
    onFilterKeyUp(fieldName, value) {
        if (fieldName != 'filter') {
            return;
        }
        value = value.toLowerCase().trim();
        this.session.request('set', 'catalogFilter', value);
        if (value.length > 1) {
            const filter = this.getFilter(value);
            this.getChildView('treeContainer').setFilter(filter);
        } else {
            this.getChildView('treeContainer').removeFilter();
        }
    },
    onToggleChecked(fieldName, value) {
        if (fieldName == 'toggle') {
            if (value) {
                this.collection.setAllSelected(this._visibleModels);
            } else {
                this.collection.setNoneSelected();
            }
        }
    }
});
export default CatalogTreeView
